package com.hitqz.robot.biz.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hitqz.robot.api.business.event.EquipmentPoseUpdateEvent;
import com.hitqz.robot.api.business.model.vo.robot.*;
import com.hitqz.robot.api.common.entity.PatrolPose;
import com.hitqz.robot.api.common.entity.RobotEquipment;
import com.hitqz.robot.api.common.entity.RobotEquipmentPose;
import com.hitqz.robot.biz.service.RobotEquipmentPoseService;
import com.hitqz.robot.biz.service.RobotEquipmentService;
import com.hitqz.robot.camera.EquipmentFactory;
import com.hitqz.robot.camera.IEquipmentService;
import com.hitqz.robot.camera.configure.EquipmentCmdEnum;
import com.hitqz.robot.camera.dto.EquipmentParamsDto;
import com.hitqz.robot.camera.dto.QueryParamsDto;
import com.hitqz.robot.common.core.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * @author wengyx
 * @date 2024/8/7
 */

@RestController
@AllArgsConstructor
@RequestMapping("/robotEquipmentPose")
@Tag(name = "机器人外设姿态管理")
public class RobotEquipmentPoseController {

    private final RobotEquipmentPoseService robotEquipmentPoseService;
    private final RobotEquipmentService robotEquipmentService;
    private final EquipmentFactory equipmentFactory;

    private final ExecutorService customThreadPool;

    @GetMapping("/list/{equipmentId}" )
    @Operation(summary = "查询机器人外设姿态列表")
    public R<List<RobotEquipmentPoseVo>> list(@PathVariable("equipmentId") Integer equipmentId) {
        List<RobotEquipmentPose> list = robotEquipmentPoseService.list();
        List<RobotEquipmentPoseVo> voList = BeanUtil.copyToList(list, RobotEquipmentPoseVo.class);
        return R.ok(voList);
    }

    @GetMapping("/{id}" )
    @Operation(summary = "根据id查询机器人外设姿态")
    public R<RobotEquipmentPoseVo> getById(@PathVariable("id") Integer id) {
        RobotEquipmentPose robotEquipmentPose = robotEquipmentPoseService.getById(id);
        RobotEquipmentPoseVo vo = BeanUtil.copyProperties(robotEquipmentPose, RobotEquipmentPoseVo.class);
        return R.ok(vo);
    }


    @GetMapping("/{id}/execute")
    @Operation(summary = "调用外设姿态")
    public R execute(@PathVariable("id") Integer id) {
        try {
            RobotEquipmentPose pose = robotEquipmentPoseService.getById(id);
            RobotEquipment equipment = robotEquipmentService.getById(pose.getEquipmentId());
            IEquipmentService service = equipmentFactory.getServiceByBrand(equipment.getBrand());
            if (service==null){
                return R.failed("找不到驱动");
            }
            //调用
            List<EquipmentParamsDto> paramsDtos = JSONArray.parseArray(pose.getJson(), EquipmentParamsDto.class);
            QueryParamsDto queryParamsDto = new QueryParamsDto();
            queryParamsDto.setPassword(equipment.getPassword());
            queryParamsDto.setUsername(equipment.getUsername());
            queryParamsDto.setPort(equipment.getPort());
            queryParamsDto.setChannel(equipment.getChannel());
            queryParamsDto.setIp(equipment.getIp());
            service.setEquipmentParams(queryParamsDto, paramsDtos, true);
            return R.ok();
        }catch (Exception e){
            return R.failed("调用姿态失败");
        }
    }


    @PostMapping
    @Operation(summary = "新增机器人外设姿态")
    public R save(@RequestBody @Validated RobotEquipmentPose dto) {
        RobotEquipmentPose pose = robotEquipmentPoseService.getOne(Wrappers.<RobotEquipmentPose>lambdaQuery()
                .eq(RobotEquipmentPose::getEquipmentId, dto.getEquipmentId())
                .eq(RobotEquipmentPose::getTypeStr, dto.getTypeStr()).last("limit 1"));
        if (pose!=null){
            return R.failed("当前姿态类型已存在");
        }
        if (robotEquipmentPoseService.save(dto)) {
            this.updateEvent(dto);
            return R.ok();
        }
        return R.failed();
    }

    @PutMapping
    @Operation(summary = "修改机器人外设姿态")
    public R updateById(@RequestBody @Validated RobotEquipmentPose dto) {
        if (robotEquipmentPoseService.updateById(dto)) {
            this.updateEvent(dto);
            return R.ok();
        }
        return R.failed();
    }

    @DeleteMapping
    @Operation(summary = "根据id删除机器人外设姿态")
    public R removeById(@RequestBody Integer[] ids) {
        return R.ok(robotEquipmentPoseService.removeBatchByIds(CollUtil.toList(ids)));
    }

    @GetMapping("/options/type" )
    @Operation(summary = "查询机器人外设姿态类型选项")
    public R<List<String>> type() {
        List<String> list = new ArrayList<>();
        list.add(EquipmentCmdEnum.GET_ORIGIN_PARAMS.getDesc());
        return R.ok(list);
    }



    private void updateEvent(RobotEquipmentPose dto){
        customThreadPool.submit(()->{
            RobotEquipment equipment = robotEquipmentService.getById(dto.getEquipmentId());
            if (equipment==null){
                return;
            }
            List<RobotEquipmentPose> list = robotEquipmentPoseService.list(Wrappers.<RobotEquipmentPose>lambdaQuery()
                    .eq(RobotEquipmentPose::getEquipmentId, dto.getEquipmentId()));
            if (list.isEmpty()){
                return;
            }
            EquipmentPoseUpdateEvent updateEvent = EquipmentPoseUpdateEvent.builder().ip(equipment.getIp()).brand(equipment.getBrand()).poseList(list).build();
            SpringUtil.getApplicationContext().publishEvent(updateEvent);
        });
    }

}
